package com.go8.goods.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.go8.common.MysqlPageWrapper;
import com.go8.goods.mapper.BrandMapper;
import com.go8.goods.mapper.ProductDetailMapper;
import com.go8.goods.mapper.ProductMapper;
import com.go8.goods.mapper.SkuMapper;
import com.go8.goods.pojo.Brand;
import com.go8.goods.pojo.Product;
import com.go8.goods.pojo.ProductDetail;
import com.go8.goods.pojo.ProductExt;
import com.go8.goods.pojo.Sku;
import com.go8.search.service.SearchService;

@Service
public class ProductServiceImpl implements ProductService {
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private ProductDetailMapper productDetailMapper;
	@Autowired
	private SkuMapper skuMapper;
	@Autowired
	private BrandMapper brandMapper;
	@Autowired
	private com.go8.goods.mapper.CatalogMapper catalogMapper;
	@Autowired
	private SearchService searchService;

	private final static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    /**
     * 全量同步
     */
    @Override
    public void syncAll() {
        List<Product> products = productMapper.selectAll();
        for (Product product:products) {
            //调用search模块同步方法：索引商品数据
            try {
                //构建索引对象
                com.go8.search.pojo.Product index = new com.go8.search.pojo.Product();
                index.setId(product.getId());
                index.setTitle(product.getTitle());
                index.setPrice(product.getPrice());
                index.setPicture(product.getPicture());
                index.setCatalog_name(catalogMapper.selectByPrimaryKey(product.getCid()).getName());
                Brand brand = brandMapper.selectByPrimaryKey(product.getBrandId());
                index.setBrand_cname(brand.getCname());
                index.setBrand_ename(brand.getEname());
                index.setAttributes(product.getAttributes());

                searchService.index(index);

                logger.info("索引商品成功");
            } catch (Exception e) {
                logger.error("索引商品失败",e);
                //再试着执行2次
                //记录日志,定时任务解决
                //人工干预解决
            }
        }
    }

    /**
     * 增量同步
	 * 添加商品的同时，调用es的商品索引接口，索引这个被添加的商品信息
	 */
	@Override
	public void add(Product product, String detail, Sku[] skus) {
		/**
		 * 添加数据到mysql
		 */
		Date now = new Date();
		product.setGmtCreate(now);
		product.setGmtModified(now);
		productMapper.insert(product);
		
		ProductDetail pdetail = new ProductDetail();
		pdetail.setProductId(product.getId());
		pdetail.setHtml(detail);
		pdetail.setGmtCreate(now);
		pdetail.setGmtModified(now);
		productDetailMapper.insert(pdetail);
		
		for(Sku sku : skus) {
			sku.setProductId(product.getId());
			sku.setGmtCreate(now);
			sku.setGmtModified(now);
			skuMapper.insert(sku);
		}
		System.out.println("添加数据库成功");
		//2种方式，调用search模块同步方法
		try {
			//构建索引对象
			com.go8.search.pojo.Product index = new com.go8.search.pojo.Product();
			index.setId(product.getId());
			index.setTitle(product.getTitle());
			index.setPrice(product.getPrice());
			index.setPicture(product.getPicture());
			index.setCatalog_name(catalogMapper.selectByPrimaryKey(product.getCid()).getName());
			Brand brand = brandMapper.selectByPrimaryKey(product.getBrandId());
			index.setBrand_cname(brand.getCname());
			index.setBrand_ename(brand.getEname());
			index.setAttributes(product.getAttributes());

            searchService.index(index);

            logger.info("索引商品成功");

			/*MQProducer producer = new MQProducer();
			producer.sendMessage("goods_group", "goods_topic", "goods_es_tag", JsonUtils.objectToJson(index).getBytes());
			System.out.println("send message success.");*/
		} catch (Exception e) {
            logger.error("索引商品失败",e);
            //再试着执行2次
            //记录日志,定时任务解决
            //人工干预解决
		}
		//System.out.println("添加商品方法调用完成");
        logger.info("添加商品方法调用完成");
	}


	@Override
	public List<Product> getProducts(int page, int size, Product product) {
		MysqlPageWrapper<Product> mpw = new MysqlPageWrapper<Product>(page, size, product);
		return productMapper.selectByPage(mpw);
	}


	@Override
	public long getCount(Product p) {
		return productMapper.selectCount(p);
	}


	@Override
	public void updatePartial(Product p) {
		productMapper.updateByPrimaryKeySelective(p);
	}


	@Override
	public Product getProductById(long id) {
		return productMapper.selectByPrimaryKey(id);
	}


	@Override
	public ProductDetail getDetailByProductId(long productId) {
		return productDetailMapper.selectByPrimaryKey(productId);
	}


	@Override
	public List<Sku> getSkusByProductId(long productId) {
		return skuMapper.selectByProductId(productId);
	}


	@Override
	public ProductExt getProductBrandById(Long id) {
		return productMapper.selectProductBrandById(id);
	}

}
